import { sliceString } from './stringUtil'

/**
 * 二分查找（有特定使用场景，请勿轻易使用）
 * @param {Array} tracks 查询数组
 * @param {Number} target 目标数字
 */
export const binarySearchTrack = (tracks, target) => {
  let start = 0
  let end = tracks.length - 1
  while (start <= end) {
    const mid = parseInt(start + (end - start) / 2)
    if ((target >= tracks[mid].startTime) && (target <= tracks[mid].endTime)) {
      return mid
    } else if (target < tracks[mid].startTime) {
      end = mid - 1
    } else {
      start = mid + 1
    }
  }
  return -1
}

/**
 * 检查字幕时间
 * @param {String} time 时间
 */
export const checkTrackTime = (time) => {
  return /^\d{2}:[0-5]\d:[0-5]\d,\d{3}$/.test(time)
}

/**
 * 格式化时间
 */
export const formatTrackTime = (time) => {
  const decimal = parseInt((time - parseInt(time)) * 1000)
  time = parseInt(time)
  const second = time % 60
  time = parseInt(time / 60)
  const minute = time % 60
  time = parseInt(time / 60)
  const hour = time
  return `${sliceString(hour, 2)}:${sliceString(minute, 2)}:${sliceString(second, 2)},${sliceString(decimal, 3)}`
}

/**
 * 实际值
 * @param {String} time 时间
 */
export const getTrackTime = (time = '00:00:31,131') => {
  const tracks = time.split(':')
  const hour = +tracks[0]
  const minute = +tracks[1]
  const second = +tracks[2].split(',')[0]
  const decimal = +tracks[2].split(',')[1]
  return hour * 3600 + minute * 60 + second + decimal / 1000
}
